import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Network } from '@ionic-native/network';
import { DeviceInfoDataService } from '../../providers/service/deviceInfo-data.service';
import { UserInfoProvider } from '../../providers/user-info/user-info';
import { OrderDataService } from '../../providers/service/order-data.service';
import { HttpProvider } from '../../providers/http/http';
import { DialogProvider } from '../../providers/dialog/dialog';

/*
  Generated class for the NetworkInformationProvider provider.

  See https://angular.io/guide/dependency-injection for more info on providers
  and Angular DI.
*/
@Injectable()
export class NetworkInformationProvider {

  // 用户信息
  userInfo: login_info = new login_info();
  
  constructor(
    public httpc: HttpClient,
    private network: Network,
    public user: UserInfoProvider,
    public deviceInfo: DeviceInfoDataService,
    public order: OrderDataService,
	public http: HttpProvider,
	public dialog: DialogProvider, ) {
    console.log('Hello NetworkInformationProvider Provider');
  }
 
  netDetect(){
    this.network.onConnect().subscribe(() => {
      if (this.network.type !== 'none' && this.network.type !== '2g') {
		// this.getMessage();
		// this.dialog.showAlert('network', (this.network.type));
        this.uploadOrder();
        this.uploadDeviceInfo();
      }
    })
  }

  	/**
	 * 上传订单
	 */
	async uploadOrder() {
		// 上传订单
		let b = await this.order.find((order) => order.key !== '' && order.upload == 0)//找出订单信息 0没有上传
		if (b.length > 0) {
			for (var i = 0; i < b.length; i++) {
				const key = b[i].key;
				b[i].index = i;
				let res = await this.http.postJson('', 'member/memberch/create', b[i], '');
				// this.dialog.showAlert('order', JSON.stringify(res));
				if (res['status'] === 200) {
					this.order.delete((a) => a.key === key);
				}
				//登录时把订单信息存入服务器
			}
			this.userInfo = this.user.getuserInfo();
			this.login();
		}
  }
  
  	/**
	 * 上传原始设备记录
	 */
	async uploadDeviceInfo() {
		// 上传原始设备记录
		let b = await this.deviceInfo.find((deviceInfo) => deviceInfo.key !== '' && deviceInfo.upload == 0)//找出订单信息 0没有上传
		if (b.length > 0) {
			for (var i = 0; i < b.length; i++) {
				const key = b[i].key;
				let time = new Date((parseInt((b[i].datetime[0] + b[i].datetime[1]), 16) + 2000), (parseInt((b[i].datetime[2] + b[i].datetime[3]), 16) - 1), parseInt((b[i].datetime[4] + b[i].datetime[5]), 16), parseInt((b[i].datetime[6] + b[i].datetime[7]), 16), parseInt((b[i].datetime[8] + b[i].datetime[9]), 16), parseInt((b[i].datetime[10] + b[i].datetime[11]), 16));
				// this.dialog.showAlert('time提示', JSON.stringify(time.getTime().toString().slice(0, 10)));
				let timeLength = time.getTime().toString().slice(0, 10);
				if (timeLength.length < 10) {
					this.deviceInfo.delete((a) => a.key === b[i].key);
					continue;
				}
				// this.dialog.showAlert('info提示', JSON.stringify(b[i]));
				let info = {
					id: b[i].rc_index,
					charge_time_start: time.getTime().toString().slice(0, 10),
					charge_time_end: (time.getTime() + (parseInt(b[i].chargingtime) * 60 * 60 * 1000)).toString().slice(0, 10),
					charge_time_org: parseInt(b[i].chargingtimerequest).toString(),
					// charge_time_start: new Date().getTime().toString().slice(0, 10),
					// charge_time_end: (new Date().getTime() + (parseInt(b[i].chargingtime) * 60 *60) ).toString().slice(0, 10),
					charge_time: parseInt(b[i].chargingtime).toString(),
					power_unit_id: b[i].power_unit_id,
					member_id: parseInt(b[i].userid),
					abnormal: b[i].abnormal,
					notifyInfo: b[i].notifyInfo,
				}
				//登录时把订单信息存入服务器
				const create = await this.http.postJson('', 'business/chargingpr/create', info, '');
				// this.dialog.showAlert('500提示', JSON.stringify(create));
				if (create['status'] === 200) {
					await this.deviceInfo.delete((a) => a.key === b[i].key);
				} else {
					if (create['code'] === 0) {
						let li = await this.deviceInfo.delete((a) => a.key === b[i].key);
						// this.dialog.showAlert('500提示', JSON.stringify(li));
					}
				}
				// if (create['status'] === 500) {
				// 	this.dialog.showAlert('500提示', JSON.stringify(key));
				// 	if (create['code'] === 2) {
				// 		this.order.delete((a) => a.key === key);
				// 	}
				// }

			}
			this.userInfo = this.user.getuserInfo();
			this.login();
		}
  }
  
  	/**
	 * 获取用户信息
	 */
	async login() {
		//   await this.storage.getStorage("login_info").then(res => {
		// 	if(res != undefined) {
		// 		this.userInfo = res;
		// 	}
		// });;
		// console.log(this.userInfo);
		const res = await this.http.postJson('', 'member/member/view?id=' + this.userInfo.member_id, {}, '')
			.then(res => {
				// console.log(res)
				if (res['status'] == 200) {
					res['data']['password'] = this.userInfo.password;
					res['data']['isAutomaticLogon'] = this.userInfo.isAutomaticLogon;
					this.userInfo = res['data'];
					this.user.setuserInfo(this.userInfo);
					// this.storage.saveStorage("login_info", res['data']);
					// this.http.setAuthorization(res['data']['access_token']);//该令牌唯一表示该用户、用户的组和用户的特权。系统使用令牌控制用户可以访问哪些安全对象，并控制用户执行相关系统操作的能力
					// this.navCtrl.push('CenterPage');
				}
			});
	}

}

export class login_info {
	member_id: any;
	nickname: any;
	phone: any;
	balance: any;
	local_balance: any;
	member_state: any;
	created_at: any;
	updated_at: any;
	cuser_id: any;
	uuser_id: any;
	is_del: any;
	password: any;
	file_type_id: any;
	access_token: any;
	isAutomaticLogon: any;
}